﻿using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows;
using Labthink.PCSoft.UniversalHost4.Model;
using Labthink.PCSoft.UniversalHost4.Model.Query;
using Labthink.PCSoft.UniversalHost4.Utility;
using Microsoft.Win32;
using Newtonsoft.Json;

namespace Labthink.PCSoft.UniversalHost4.UserControls
{
    public partial class UcDataManage
    {
        public UcDataManage()
        {
            InitializeComponent();
        }

        private NotifyManager _notify;

        public string Title { get; set; } = LanguageManager.GetLanguageValue("DataManage");

        public string PermissionCode { get; set; } = "Per_DataManage";

        private void DataManage_OnLoaded(object sender, RoutedEventArgs e)
        {
            DpeStart.DpPicker.SelectedDate = DateTime.Now.AddMonths(-12);
            DpeEnd.DpPicker.SelectedDate = DateTime.Now;

            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }

            var w = Window.GetWindow(this);
            _notify = NotifyManager.InstanceManager(w);

            if (Common.BaseInfo.AutoReport)
            {
                BtnAutoUpdate.Visibility = Visibility;
            }
        }

        private async void BtnRestoreData_OnClick(object sender, RoutedEventArgs e)
        {
            _triggerButtonsStatus(false);

            var open = new OpenFileDialog
            {
                Multiselect = false
            };

            var result = open.ShowDialog();
            if (result != null && result.Value)
            {
                var file = open.FileName;
                var str = await Common.Instrument.Commands.RestoreTestDataFromPcAsync(file);
                if (str.StartsWith("--"))
                {
                    try
                    {
                        var sd = JsonConvert.DeserializeObject<SocketData>(str.Remove(0, 2));
                        _notify.ShowError(sd.ErrorMsg);
                    }
                    catch
                    {
                        _notify.ShowError(str.Replace("--", ""));
                    }
                }
                else
                {
                    _notify.ShowSuccess(str);
                }
            }

            _triggerButtonsStatus(true);
        }

        private async void BtnBackup_OnClick(object sender, RoutedEventArgs e)
        {
            _triggerButtonsStatus(false);
            var qb = new QueryBackup
            {
                // ReSharper disable once PossibleInvalidOperationException
                Start = DpeStart.DpPicker.SelectedDate.Value,
                // ReSharper disable once PossibleInvalidOperationException
                End = DpeEnd.DpPicker.SelectedDate.Value
            };

            var str = await Common.Instrument.Commands.BackupTestDataFromPcAsync(qb);
            if (string.IsNullOrEmpty(str.file))
            {
                if (string.IsNullOrEmpty(str.result))
                {
                    _notify.ShowError(LanguageManager.GetLanguageValue("ActionFail"));
                }
                else if (str.result == "0")
                {
                    _notify.ShowSuccess(LanguageManager.GetLanguageValue("ActionSuccess"));
                }
                else
                {
                    _notify.ShowError(str.result);
                }
            }
            else
            {
                var save = new SaveFileDialog
                {
                    RestoreDirectory = true,
                    FileName = Path.GetFileName(str.file)
                };

                var result = save.ShowDialog(Application.Current.MainWindow);
                if (result.Value)
                {
                    File.Move(str.file, save.FileName);
                    _notify.ShowSuccess(LanguageManager.GetLanguageValue("ActionSuccess"));
                }
            }
            _triggerButtonsStatus(true);
        }

        private void _triggerButtonsStatus(bool status)
        {
            BtnBackupData.IsEnabled = status;
            BtnAutoUpdate.IsEnabled = status;
            BtnRestoreData.IsEnabled = status;
            if (status) Loading.Visibility = Visibility.Collapsed;
            else Loading.Visibility = Visibility.Visible;
        }
    }
}
